package com.xiguaji.boot.data.rdb;

import com.xiguaji.boot.data.rdb.aggregate.Aggregate;
import com.xiguaji.boot.toolkit.DateTimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.*;
import org.springframework.data.jdbc.repository.support.SimpleJdbcRepository;
import org.springframework.data.relational.core.mapping.event.BeforeSaveEvent;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

@Configuration
@ConditionalOnClass(SimpleJdbcRepository.class)
@Slf4j
public class RdbConfiguration {

    @Bean("rdbTemplate")
    @Primary
    public JdbcTemplate rdbTemplate(@Qualifier("rdbDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    @Bean("rdbDataSource")
    @ConfigurationProperties(prefix = "spring.rdb")
    @Primary
    public DataSource rdbDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    public ApplicationListener<BeforeSaveEvent<Object>> beforeSaveEventApplicationListener() {
        return event -> {
            Aggregate aggregate = (Aggregate) event.getEntity();
            long currentTimeSecond = DateTimeUtils.currentTimeSecond();
            if (aggregate.getId() <= 0) {
                aggregate.generator(currentTimeSecond);
            }
            aggregate.setUpdateTime(currentTimeSecond);
        };
    }

}
